<?php
/**
 * 简化版轮播图API
 * 减少依赖，直接使用数据库连接
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'code' => 500,
        'success' => false,
        'message' => '数据库连接失败',
        'data' => null,
        'timestamp' => time()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 分页处理
function paginate($page = 1, $limit = 20) {
    $page = max(1, intval($page));
    $limit = min(100, max(1, intval($limit)));
    $offset = ($page - 1) * $limit;
    
    return [
        'page' => $page,
        'limit' => $limit,
        'offset' => $offset
    ];
}

// 处理请求
$action = $_GET['action'] ?? 'list';

try {
    switch ($action) {
        case 'list':
            // 获取轮播图列表
            $pagination = paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 20);
            $status = $_GET['status'] ?? 'active';
            
            $sql = "SELECT id, title, image_url, link_type, link_value, sort, status, 
                           view_count, created_at, updated_at 
                    FROM carousels 
                    WHERE status = :status 
                    ORDER BY sort ASC, id DESC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['status' => $status]);
            $carousels = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM carousels WHERE status = :status";
            $countStmt = $pdo->prepare($countSql);
            $countStmt->execute(['status' => $status]);
            $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
            
            // 格式化数据
            foreach ($carousels as &$carousel) {
                $carousel['view_count'] = intval($carousel['view_count']);
                $carousel['sort'] = intval($carousel['sort']);
            }
            
            success([
                'list' => $carousels,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            break;
            
        case 'detail':
            // 获取轮播图详情
            $id = $_GET['id'] ?? '';
            if (empty($id)) {
                error('缺少轮播图ID');
            }
            
            $sql = "SELECT * FROM carousels WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['id' => $id]);
            $carousel = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$carousel) {
                error('轮播图不存在', 404);
            }
            
            // 更新浏览次数
            $updateSql = "UPDATE carousels SET view_count = view_count + 1 WHERE id = :id";
            $updateStmt = $pdo->prepare($updateSql);
            $updateStmt->execute(['id' => $id]);
            
            $carousel['view_count'] = intval($carousel['view_count']) + 1;
            $carousel['sort'] = intval($carousel['sort']);
            
            success($carousel);
            break;
            
        case 'click':
            // 记录点击
            $id = $_POST['id'] ?? $_GET['id'] ?? '';
            if (empty($id)) {
                error('缺少轮播图ID');
            }
            
            // 验证轮播图存在
            $sql = "SELECT id, link_type, link_value FROM carousels WHERE id = :id AND status = 'active'";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['id' => $id]);
            $carousel = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$carousel) {
                error('轮播图不存在或已下线', 404);
            }
            
            // 更新点击次数
            $updateSql = "UPDATE carousels SET click_count = click_count + 1 WHERE id = :id";
            $updateStmt = $pdo->prepare($updateSql);
            $updateStmt->execute(['id' => $id]);
            
            // 记录点击日志（如果表存在）
            try {
                $logSql = "INSERT INTO carousel_clicks (carousel_id, user_ip, user_agent, clicked_at) 
                          VALUES (:carousel_id, :user_ip, :user_agent, NOW())";
                $logStmt = $pdo->prepare($logSql);
                $logStmt->execute([
                    'carousel_id' => $id,
                    'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);
            } catch (Exception $e) {
                // 日志记录失败不影响主要功能
            }
            
            success([
                'link_type' => $carousel['link_type'],
                'link_value' => $carousel['link_value']
            ], '点击记录成功');
            break;
            
        default:
            error('无效的操作');
    }
    
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>